<template>
    <van-address-list
        v-model="AddressId"
        :list="list"
        default-tag-text="默认"
        @add="OnAdd"
        @edit="OnEdit"
        @select="OnSelect"
    />

</template>

<script setup>
const { proxy } = getCurrentInstance();

const business = proxy.$business;
const list = ref([]);
const AddressId = ref(0);
const action = ref(proxy.$route.query.action ?? '');

onBeforeMount(() => GetAddressData());

const GetAddressData = async () =>
{
    let params = {
        busid:business.value.id
    }

    let result = await proxy.$http.post({
        url:'/address/index',
        params
    })

    if(result.code === 1)
    {
        let data = [];

        for(let item of result.data)
        {
            data.push({
                id:item.id,
                name:item.consignee,
                tel:item.mobile,
                address:item.region_text + item.address,
                isDefault:item.status == 1 ? true : false
            })

            if(item.status == 1)
            {
                AddressId.value = item.id;
            }
        }

        list.value = data;
    }
}

const OnAdd = () => proxy.$router.push('/address/add');

const OnEdit = (info) => proxy.$router.push({path:'/address/edit',query:{addrid:info.id}});

const OnSelect = async (info,index) =>
{
    if(action.value === 'confirm')
    {
        // 从确认订单
        const address = {
            id:info.id,
            name:info.name,
            tel:info.tel,
            region_text:info.address
        }

        proxy.$address.value = address;

        proxy.$router.back();
    }else{
        // 从收货地址列表过来
        let params = {
            id:info.id,
            busid:business.value.id
        }

        let result = await proxy.$http.post({
            url:'/address/select',
            params
        })

        if(result.code === 1)
        {
            GetAddressData();
        }else{
            proxy.$fail(result.msg);
        }
    }
}

</script>